from django_redis import get_redis_connection
from utils.dictconvert import loads

"""将cookies中的数据写入redis"""


def merge_cart_cookie2redis(request, response, user_id):
    cart = request.COOKIES.get('cart')
    if not cart:
        return response
    cart_dict = loads(cart)
    redis_cli = get_redis_connection('cart')
    # 遍历cookie 是一个字典
    for sku_id, dict_info in cart_dict.items():
        # 将sku_id count写入hash
        redis_cli.hset('cart%d' % user_id, sku_id, dict_info["count"])
        #  sku_id selected 写入set
        if dict_info["selected"]:
            redis_cli.sadd('cart_selected%d' % user_id, sku_id)
        else:
            redis_cli.srem('cart_selected%d' % user_id, sku_id)
    # 将cookies中的数据删除
    response.delete_cookie('cart')
    return response
